﻿using Dapper;
using Entity;
using Microsoft.Extensions.Logging; // 引入日志命名空间
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Threading.Tasks;
using XingWeiDaWMSProject.IRepository;

namespace XingWeiDaWMSProject.Repository
{
    public class SysOrgUserManagementRepository : ISysOrgUserManagementRepository
    {
        // 保持IDbConnection类型不变
        private readonly IDbConnection _dbConnection;
        // 新增：日志字段（解决_logger未定义问题）
        private readonly ILogger<SysOrgUserManagementRepository> _logger;

        // 构造函数注入IDbConnection和日志（适配依赖注入）
        public SysOrgUserManagementRepository(IDbConnection dbConnection, ILogger<SysOrgUserManagementRepository> logger)
        {
            _dbConnection = dbConnection;
            _logger = logger; // 初始化日志
        }

        // 根据账号查询用户（含关联岗位/部门）
        public async Task<SysOrgUserManagement> GetByUserAccountAsync(string userAccount)
        {
            string sql = @"
                SELECT 
                    sum.user_id as UserId,
                    sum.user_account as UserAccount,
                    sum.user_name as UserName,
                    sum.user_avatar as UserAvatar,
                    sum.sex as Sex,
                    sum.phone_number as PhoneNumber,
                    sum.roles_id as RolesId,
                    sum.sorting as Sorting,
                    sum.note as Note,
                    sum.status as Status,
                    sum.create_by as CreateBy,
                    sum.create_time as CreateTime,
                    sum.update_by as UpdateBy,
                    sum.update_time as UpdateTime,
                    sum.is_delete as IsDelete,
                    sum.job_id as JobId,
                    sum.organization_id as OrganizationId,
                    sum.user_password as UserPassword,
                    post.job_title as JobName,
                    org.organization_name as DepartmentName
                FROM sys_org_user_management sum
                LEFT JOIN sys_org_post_management post ON sum.job_id = post.job_id
                LEFT JOIN sys_org_organizations org ON sum.organization_id = org.organization_id
                WHERE sum.user_account = @UserAccount AND sum.is_delete = '0'";

            return await _dbConnection.QueryFirstOrDefaultAsync<SysOrgUserManagement>(
                sql,
                new { UserAccount = userAccount }
            );
        }

        // 更新用户基本信息（不含密码）
        public async Task<bool> UpdateAsync(SysOrgUserManagement user)
        {
            string sql = @"
                UPDATE sys_org_user_management  
                SET user_name = @UserName, 
                    sex = @Sex, 
                    phone_number = @PhoneNumber, 
                    user_avatar = @UserAvatar, 
                    update_by = @UpdateBy, 
                    update_time = @UpdateTime 
                WHERE user_id = @UserId AND is_delete = '0'";

            int affectedRows = await _dbConnection.ExecuteAsync(sql, new
            {
                user.UserId,
                user.UserName,
                user.Sex,
                user.PhoneNumber,
                user.UserAvatar,
                user.UpdateBy,
                user.UpdateTime
            });
            return affectedRows > 0;
        }

        // 验证密码（加密后匹配）
        public async Task<bool> VerifyPasswordAsync(string userAccount, string encryptedPassword)
        {
            string sql = @"
                SELECT COUNT(1) FROM sys_org_user_management  
                WHERE user_account = @UserAccount 
                  AND user_password = @EncryptedPassword 
                  AND is_delete = '0'
                  AND status = '1'";

            int count = await _dbConnection.ExecuteScalarAsync<int>(
                sql,
                new { UserAccount = userAccount, EncryptedPassword = encryptedPassword }
            );
            return count > 0;
        }

        // 修改密码
        public async Task<bool> ChangePasswordAsync(string userAccount, string encryptedNewPassword, string updateBy, DateTime updateTime)
        {
            string sql = @"
                UPDATE sys_org_user_management  
                SET user_password = @EncryptedNewPassword, 
                    update_by = @UpdateBy, 
                    update_time = @UpdateTime 
                WHERE user_account = @UserAccount 
                  AND is_delete = '0'
                  AND status = '1'";

            int affectedRows = await _dbConnection.ExecuteAsync(sql, new
            {
                UserAccount = userAccount,
                EncryptedNewPassword = encryptedNewPassword,
                UpdateBy = updateBy,
                UpdateTime = updateTime
            });
            return affectedRows > 0;
        }

        public async Task<string> GetPasswordByAccountAsync(string userAccount)
        {
            string sql = @"
                SELECT user_password 
                FROM sys_org_user_management 
                WHERE user_account = @UserAccount 
                  AND is_delete = '0' 
                  AND status = '1'";

            return await _dbConnection.QueryFirstOrDefaultAsync<string>(
                sql,
                new { UserAccount = userAccount }
            );
        }

        /// <summary>
        /// 查询所有未删除的用户
        /// </summary>
        public async Task<List<SysOrgUserManagement>> GetAllAsync()
        {
            string sql = @"
                SELECT 
                    user_id as UserId,
                    user_account as UserAccount,
                    user_name as UserName,
                    user_avatar as UserAvatar,
                    sex as Sex,
                    phone_number as PhoneNumber,
                    roles_id as RolesId,
                    sorting as Sorting,
                    note as Note,
                    status as Status,
                    create_by as CreateBy,
                    create_time as CreateTime,
                    update_by as UpdateBy,
                    update_time as UpdateTime,
                    is_delete as IsDelete,
                    job_id as JobId,
                    organization_id as OrganizationId,
                    user_password as UserPassword
                FROM sys_org_user_management
                WHERE is_delete = '0'
                ORDER BY sorting ASC, create_time DESC";

            var result = await _dbConnection.QueryAsync<SysOrgUserManagement>(sql);
            return result.AsList();
        }

        // 获取具有“库位主管”角色的用户
        public async Task<List<SysOrgUserManagement>> GetByRoleNameAsync(string roleName)
        {
            var roleSql = "SELECT role_id FROM sys_org_role_management WHERE character_name = @RoleName AND is_delete = 0";
            var roleId = await _dbConnection.QueryFirstOrDefaultAsync<int>(roleSql, new { RoleName = roleName });
            Debug.WriteLine($"查询角色ID结果：roleName={roleName}，roleId={roleId}");

            if (roleId == 0)
            {
                Debug.WriteLine("未查询到角色ID，返回空列表");
                return new List<SysOrgUserManagement>();
            }

            var userRoleSql = "SELECT user_id FROM sys_org_user_role WHERE role_id = @RoleId";
            var userIds = (await _dbConnection.QueryAsync<int>(userRoleSql, new { RoleId = roleId })).ToList();
            Debug.WriteLine($"查询用户ID结果：roleId={roleId}，userIds={string.Join(",", userIds)}");

            if (!userIds.Any())
            {
                Debug.WriteLine("未查询到关联的用户ID，返回空列表");
                return new List<SysOrgUserManagement>();
            }

            var userSql = @"
SELECT 
    user_id as UserId,
    user_name as UserName,
    user_account as UserAccount,
    status as Status,
    is_delete as IsDelete,
    phone_number as PhoneNumber
FROM sys_org_user_management 
WHERE user_id IN @UserIds AND is_delete = 0";

            var users = (await _dbConnection.QueryAsync<SysOrgUserManagement>(userSql, new { UserIds = userIds })).ToList();

            Debug.WriteLine($"查询用户信息结果：共{users.Count}条");
            foreach (var user in users)
            {
                Debug.WriteLine($"UserId={user.UserId}, UserName={user.UserName}, PhoneNumber={user.PhoneNumber}");
            }

            return users;
        }

        // 实现：根据用户ID查询用户（修正后）
        public async Task<SysOrgUserManagement> GetByIdAsync(int userId)
        {
            try
            {
                // 修正：IDbConnection无OpenAsync，使用同步Open方法（不影响整体异步流程）
                if (_dbConnection.State != ConnectionState.Open)
                {
                    _dbConnection.Open(); // 同步打开连接
                }

                // 明确查询需要的字段（避免SELECT *的潜在问题）
                var sql = @"
                    SELECT 
                        user_id as UserId,
                        user_name as UserName,
                        phone_number as PhoneNumber,
                        user_account as UserAccount,
                        status as Status,
                        is_delete as IsDelete
                    FROM sys_org_user_management 
                    WHERE user_id = @UserId 
                      AND is_delete = '0'";

                // 执行查询并返回结果
                return await _dbConnection.QueryFirstOrDefaultAsync<SysOrgUserManagement>(
                    sql,
                    new { UserId = userId }
                );
            }
            catch (Exception ex)
            {
                // 修正：使用注入的_logger记录错误
                _logger.LogError(ex, "根据ID查询用户失败，用户ID：{UserId}", userId);
                throw; // 抛出异常让上层处理
            }
        }
        // 关键实现：批量查询用户ID对应的名称
        public async Task<Dictionary<string, string>> GetUserNamesByIdsAsync(List<string> userIds)
        {
            if (userIds == null || !userIds.Any())
                return new Dictionary<string, string>();

            // 修正：IN子句去掉手动括号，Dapper自动处理列表参数
            var sql = @"SELECT 
                    CAST(user_id AS VARCHAR(50)) AS user_id,
                    user_name 
               FROM sys_org_user_management 
               WHERE user_id IN @UserIds  -- 正确写法：无括号
                 AND is_delete = '0'";

            try
            {
                // 执行查询（Dapper会自动将userIds转换为('id1','id2',...)格式）
                var userList = await _dbConnection.QueryAsync<(string user_id, string user_name)>(
                    sql,
                    new { UserIds = userIds }  // 直接传递List<string>参数
                );

                return userList.ToDictionary(
                    item => item.user_id,
                    item => string.IsNullOrEmpty(item.user_name) ? "未知用户" : item.user_name
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetUserNamesByIdsAsync错误：SQL={sql}，参数={string.Join(",", userIds)}，错误={ex.Message}");
                throw;
            }
        }
    }
}